import com.alibaba.fastjson.JSON;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.EventLoop;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;
import org.nettyServer.command.CommandBase;
import org.nettyServer.command.heartbeat.CS_Heartbeat;
import org.nettyServer.command.login.CS_Login;
import org.nettyServer.eunm.EMessageCode;
import org.nettyServer.messageHandle.PushUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

import static io.netty.handler.codec.smtp.SmtpRequests.data;

@Component
@Slf4j
@ChannelHandler.Sharable
public class ClientHandler extends SimpleChannelInboundHandler {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws InterruptedException {
        InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIP = insocket.getAddress().getHostAddress();
        String message = new String((byte[]) msg, StandardCharsets.UTF_8);
        log.info("服务器ip: {},信道: {} 收到消息: {}", clientIP,ctx.channel().id(), message);
//        Thread.sleep(5000);

        CommandBase commandBase = JSON.parseObject(message, CommandBase.class);
        if (commandBase.getCommandCode().equals(EMessageCode.HEARTBEAT.getCode())) {
            ClientPushUtils.pushMessage(EMessageCode.HEARTBEAT.getCode(), new CS_Heartbeat(), ctx.channel());
        }

    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    }


    /**
     * 通道连接时调用-处理业务逻辑
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIP = insocket.getAddress().getHostAddress();
        log.info("服务器ip: {} ：通道已连接！", clientIP);

        CS_Login csLogin = new CS_Login();
        csLogin.setUserName("admin");

        ClientPushUtils.pushMessage(EMessageCode.LOGIN.getCode(), csLogin, ctx.channel());
    }

    /**
     * 通道闲置触发-启动断线重连功能
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        //使用过程中断线重连
        final EventLoop eventLoop = ctx.channel().eventLoop();
        eventLoop.schedule(() -> {
            log.error("服务器连接断开");
//            createTCPConnection.run();
        }, 1, TimeUnit.SECONDS);
        ctx.fireChannelInactive();
    }

    /**
     * 心跳方法
     * @param ctx
     * @param evt
     * @throws Exception
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {

        }
        super.userEventTriggered(ctx, evt);
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        super.handlerAdded(ctx);
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        super.handlerRemoved(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.error("服务器连接异常,{}", cause.getMessage());
//        super.exceptionCaught(ctx, cause);
    }
    private  byte[] getSendMessage(String message) throws IOException {
        return (message+"1111111111"+"\n").getBytes();
    }
}
